#include <bits/stdc++.h>
using namespace std;

const int maxn = 5e6 + 5;
typedef long long ll;

inline void read(int &x) {
    int s = 0, w = 1;
    char ch = getchar();
    while (ch < '0' || ch > '9') {
        if (ch == '-')
            w = -1;
        ch = getchar();
    }
    while (ch >= '0' && ch <= '9') {
        s = (s * 10) + ch - '0';
        ch = getchar();
    }
    x = s * w;
}

ll frac[maxn];

ll qpow(ll base, ll exponent) {
    ll result = 1;
    while (exponent > 0) {
        if (exponent % 2 == 1) {
            result = (result * base);
        }
        base = (base * base);
        exponent /= 2;
    }
    return result;
}

ll c(ll n, ll m,ll p) {
    if (m > n||n==0) {
        return 0;
    }
    if(m==0)
    return 1;
    return frac[n] * qpow(frac[m], p) % p * qpow(frac[n - m], p);
}

ll lucas(ll n, ll m,ll p) {
    if (n<p&&m<p) {
        return c(n,m,p);
    }
    return lucas(n / p, m / p,p) * c(n %p, m %p,p) % p;
}

int main() {
    int t;
    read(t);
    
    frac[0] = 1;
    for (int i = 1; i <= 100000; i++) {
        frac[i] = (frac[i - 1] * i);
    }

    ll ans = 0;
    while (t--) {
        int n, m, p;
        read(n);
        read(m);
        read(p);
        cout << lucas(n, m,p) << endl;
    }
    return 0;
}
